package com.vise.bledemo.jky;

import static java.lang.Thread.sleep;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.vise.baseble.ViseBle;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.callback.scan.ScanCallback;
import com.vise.baseble.common.PropertyType;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.model.BluetoothLeDeviceStore;
import com.vise.bledemo.BTConfig;
import com.vise.bledemo.R;
import com.vise.bledemo.activity.DeviceDetailActivity;
import com.vise.bledemo.common.BluetoothDeviceManager;
import com.vise.bledemo.common.ToastUtil;
import com.vise.bledemo.event.ConnectEvent;
import com.vise.bledemo.utils.ConvertUtil;
import com.vise.log.ViseLog;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.event.Subscribe;

import java.util.UUID;

public class BLEDeviceConnectActivity extends BaseBLEActivity {


    ImageView imageView;
    ProgressDialog progressDialog;
    TextView textView;

    String BTName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deviceconnect);
        BusManager.getBus().register(BLEDeviceConnectActivity.this);
        mDevice = getIntent().getParcelableExtra(DeviceDetailActivity.EXTRA_DEVICE);
        BTName = mDevice.getDevice().getName();
        textView1 = findViewById(R.id.textView1);
        textView1.setText(showInputtext);
        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (!BluetoothDeviceManager.getInstance().isConnected(mDevice)) {
//                    stopScan();
//                    progressDialog = ProgressDialog.show(BLEDeviceConnectActivity.this, "蓝牙操作提示", "蓝牙连接中 ..."
//                            , false, true);
//                    BluetoothDeviceManager.getInstance().connect(mDevice);
//                } else {
//                    ToastUtil.showToast(BLEDeviceConnectActivity.this, "蓝牙已经连接完毕!");
//                }
                showInputtext = "开始\n\n";
                if (isAttain == false) {
                    ToastUtil.showToast(BLEDeviceConnectActivity.this, "请靠近蓝牙设备，必须信号强大高于" + BTConfig.RssiMAX + "-dB");
                    return;
                }
                stopScan();
                handler.obtainMessage(1, true).sendToTarget();
            }
        });
        textView.setText("信号强度:" + mDevice.getRssi() + "dB");
    }

    @Override
    protected void onResume() {
        super.onResume();
        startScan();
    }


    @Override
    protected void onPause() {
        super.onPause();
        stopScan();
    }

    private boolean isReadRssi = true;

    private void startScan() {
        isReadRssi = true;
        ViseBle.getInstance().startScan(periodScanCallback);
    }

    private void stopScan() {
        isReadRssi = false;
        ViseBle.getInstance().stopScan(periodScanCallback);
    }


    boolean isAttain = false;
    private long lasttime = 0;
    private ScanCallback periodScanCallback = new ScanCallback(new IScanCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onDeviceFound(final BluetoothLeDevice bluetoothLeDevice) {
            Log.e("", "BTAddress  " + BTName + "   scan-> " + bluetoothLeDevice.getDevice().getName() + "  扫描信号强度" + bluetoothLeDevice.getRssi() + "dB");
            if (BTName.equals(bluetoothLeDevice.getDevice().getName())) {
                ToastUtil.showToast(BLEDeviceConnectActivity.this, "扫描信号强度" + bluetoothLeDevice.getRssi() + "dB");

                if (Math.abs(bluetoothLeDevice.getRssi()) < BTConfig.RssiMAX) {
                    isAttain = true;
                    if (System.currentTimeMillis() - lasttime > BTConfig.OUTTime) {
                        ToastUtil.showToast(BLEDeviceConnectActivity.this, "已经靠近设备");
                        lasttime = System.currentTimeMillis();
                        Vibrator vibrator = (Vibrator) BLEDeviceConnectActivity.this.getSystemService(BLEDeviceConnectActivity.VIBRATOR_SERVICE);
                        vibrator.vibrate(200);
                    }
                }


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("信号强度 " + bluetoothLeDevice.getRssi() + "dB");
                    }
                });
            }
        }

        @Override
        public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
            ViseLog.i("scan finish " + bluetoothLeDeviceStore);
        }

        @Override
        public void onScanTimeout() {
            ViseLog.i("scan timeout");
        }

    });

    @Subscribe
    public void showConnectedDevice(ConnectEvent event) {
        if (event != null) {
            progressDialog.dismiss();
            if (event.isSuccess()) {
                ToastUtil.showToast(BLEDeviceConnectActivity.this, "蓝牙连接成功!");
//                BLEDeviceControlActivity.startBLEDeviceControlActivity(BLEDeviceConnectActivity.this);
//                BusManager.getBus().unregister(BLEDeviceConnectActivity.this);
//                finish();
                handler.sendEmptyMessageAtTime(3, 500);
            } else {
                if (event.isDisconnected()) {
                    ToastUtil.showToast(BLEDeviceConnectActivity.this, "蓝牙断开成功!");
                } else {
                    ToastUtil.showToast(BLEDeviceConnectActivity.this, "蓝牙连接失败!");
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopScan();
        BluetoothDeviceManager.getInstance().disconnect(mDevice);
        BusManager.getBus().unregister(BLEDeviceConnectActivity.this);
    }


    /////////////////////////////////

    TextView textView1;
    String showInputtext = "开始\n\n";

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    showInputtext = showInputtext + "1、搜索到设备控制器\n\n";
                    textView1.setText(showInputtext);
                    handler.sendEmptyMessageAtTime(2, 1000);
                    break;

                case 2:
                    showInputtext = showInputtext + "2、连接到设备控制器\n\n";
                    textView1.setText(showInputtext);
                    if (!BluetoothDeviceManager.getInstance().isConnected(mDevice)) {
                        progressDialog = ProgressDialog.show(BLEDeviceConnectActivity.this, "蓝牙操作提示", "蓝牙连接中 ..."
                                , false, true);
                        BluetoothDeviceManager.getInstance().connect(mDevice);
                    } else {
                        ToastUtil.showToast(BLEDeviceConnectActivity.this, "蓝牙已经连接完毕!");
                        handler.sendEmptyMessageAtTime(3, 1000);
                    }
                    break;

                case 3:
                    showInputtext = showInputtext + "3、发送控制指令\n\n";
                    textView1.setText(showInputtext);
                    initBT();
                    handler.sendEmptyMessageAtTime(4, 1000);
                    break;
                case 4:
                    showInputtext = showInputtext + "4、设备操作完毕\n\n";
                    textView1.setText(showInputtext);
                    String temp = "LKO";
                    BluetoothDeviceManager.getInstance().write(mDevice, ConvertUtil.hexStr2Bytes(ConvertUtil.str2HexStr(temp)));
                    break;
            }
        }
    };

    private void initBT() {
        if (mDevice != null && BluetoothDeviceManager.getInstance().isConnected(mDevice)) {
            ToastUtil.showToast(this, "蓝牙链接成功 执行写入服务！！！");
            BluetoothDeviceManager.getInstance().bindChannel(mDevice, PropertyType.PROPERTY_WRITE,
                    UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),
                    UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"), null);
//            BluetoothDeviceManager.getInstance().bindChannel(mDevice, PropertyType.PROPERTY_NOTIFY, UUID.fromString("19b10001-e8f2-537e-4f6c-d104768a1214"), UUID.fromString("19b10001-e8f2-537e-4f6c-d104768a1214"), null);
//            BluetoothDeviceManager.getInstance().write(BTListRecycleViewAdapter.selectBTDevices, HexUtil.decodeHex("22110000".toString().toCharArray()));
        } else {
            ToastUtil.showToast(this, "没有选择蓝牙设备！！！");
        }
    }

}